import Taro, { Component } from '@tarojs/taro'
import { View, ScrollView, Text } from '@tarojs/components'
import { AtTabs, AtInput, AtTabsPane, AtButton, AtActionSheet, AtActionSheetItem } from 'taro-ui'
import { DNavBar, Dmorinfo, DAtInpute, DItemError, DModal, Ddialog } from '@/components'
import PropsType from 'prop-types'

import http from '@/api'
import common from '@/common'
import '../index/index.scss'
import './mortgage.scss'
import '../drawback/drawback.scss'
const belongToBankList = require('@/common/').default.belongbankList
export default class DMortgageList extends Component {

  constructor(props) {
    super(props)
    this.state = {
      // active: 0,
      isShow: false,
      scrollHeight: window.screen.availHeight,
      id: '',
      handle: '',
      currPage: 1,
      totalPage: 1,
      pageSize: 10,
      status: false,
      signBankisOpened: false,
      isOpened: false, //筛选
      form: {
        carModelName: '',
        signBank: '',
        minPrice: '',
        maxPrice: ''

      },

      list: [],
      itemId: '',
      showDialog: false
    }
  }

  componentWillMount() {
    // this.httpMySearchCarList()
    // let { active = 0 } = this.props
  }
  componentWillReceiveProps(props, prop) {
    let active = props.active
    if (props.active !== undefined) {
      this.setState({
        // list: [],
        currPage: 1,
        totalPage: 1,
        active,
        status: false
      }, () => this.httpMySearchCarList(false, +props.active))

    }
  }
  componentDidShow() {
    this.setState({
      list: [],
      currPage: 1,
      totalPage: 1,
      status: false
    }, () => {

      this.httpMySearchCarList()
    })
  }

  //寻车详细
  handleDetail(item) {
    // let { active } = this.state
    // if (active === 1) {
    //   return Taro.showToast({
    //     title: '该寻车已过期',
    //     icon: 'none'
    //   })
    // }
    let { status } = this.props
    let paramsStatus = ''
    if (status) paramsStatus = `status=${status}`
    Taro.navigateTo({
      url: `/pages/mortgage/applyform?id=${item.id}&${paramsStatus}`
    })
  }
  //切换tab
  handleClick(active) {
    this.setState({
      list: [],
      currPage: 1,
      totalPage: 1,
      active,
      status: false
    }, () => this.httpMySearchCarList())
  }

  //跳转
  async onHandleForm() {
    const { eaIsAppro } = await http.getConfirmInfo()
    const { imIdStatus } = await http.myselfDetail()

    if (eaIsAppro == 1 || imIdStatus == 2) {
      Taro.navigateTo({
        url: `/pages/mortgage/applyform`
      })
    } else {
      this.setState({
        showDialog: true
      })
    }

  }
  filterSearch(carModelName) {
    const { form } = this.state
    this.setState({
      form: { ...form, carModelName }
    }, () => this.handleClick(this.state.active)
    )
  }
  httpMySearchCarList = (isAppend = false, active) => {
    const { pageSize, currPage, totalPage, form } = this.state
    const { id } = this.$router.params
    if (!active && active !== 0) {
      active = this.props.active
    }
    if (currPage > totalPage && isAppend) {
      return this.setState({
        status: true
      })
    }
    let _http

    if (!id) {
      let obj = {
        signBank: form.signBank,
        carModelName: form.carModelName
      }
      form.minPrice ? obj.minPrice = form.minPrice : ''
      form.maxPrice ? obj.maxPrice = form.maxPrice : ''
      _http = http.appGetList({
        limit: pageSize,
        page: currPage,
        status: active,
        ...obj
      })
    } else if (active > 1) {

      _http = http.getSearchMortgages({
        limit: pageSize,
        page: currPage,
        entId: id || ''
      })

    }

    _http && _http.then(res => {
      let arr = []
      // if(id&&res.list.length){

      //  res.list.forEach(item=>{
      //   if(item.entId==id){
      // 	  arr.push(list)
      //   }

      //  })
      //  res.totalCount = arr.length
      // }
      if (isAppend) {
        const { list } = this.state
        res.list = [...list, ...res.list]
      }
      ////debugger
      this.setState({
        ...res,
        status: false
      })
      ////debugger
    })
  }
  onFirstClick(item) {
    const { active } = this.props
    if (active === 0) {
      this.setState({
        isShow: true,
        handle: '取消申请',
        itemId: item.id
      })
    } else if (active === 1) {
      // this.setState({
      //   isShow: true,
      //   handle: '删除',
      //   itemId: item.id
      // })
    }
  }
  onScrollEnd = () => {
    this.setState({
      currPage: this.state.currPage + 1
    }, () => this.httpMySearchCarList(true))
  }

  //关闭改价框/模态框
  onCancelHandle = () => {
    this.setState({
      isShow: false
    })
  }

  //模态框确认按钮
  onDelHandle() {
    this.onCancelHandle()
    const { itemId, active } = this.state
    http.cancelApply({
      id: itemId
    }).then(res => {
      if (res) {
        Taro.showToast({
          title: '取消成功！',
          duration: 800
        }).then(() => {
          setTimeout(() => {
            this.setState({
              currPage: 1,
              list: [],
              totalPage: 1
            }, () => {
              this.httpMySearchCarList()
              // Taro.redirectTo({
              //   url: `/pages/martgage/martgage?active=0`
              // })
            })
          }, 1000)
        })
      } else {
        Taro.showToast({
          icon: 'none',
          title: '取消失败！'
        })
      }
    })

  }
  onClickAction() {
    this.onClickAction()
  }
  handleActionSheet(signBank) {
    let { form } = this.state
    form.signBank = signBank
    this.setState({
      form,
      signBankisOpened: false
    })
  }
  onHandleSelect() {

    this.setState({
      signBankisOpened: true
    })
  }
  filterTime(item) {
    var minute = 1000 * 60;
    var hour = minute * 60;
    // var day = hour * 24;
    // var halfamonth = day * 15;
    // var month = day * 30;

    let h = 0
    h = (new Date().getTime() - new Date(item.createTime).getTime()) / hour

    return parseInt(h) || 0
  }
  handCloseSix(e, i) {
    if (i) {
      this.setState({
        form: {
          carModelName: '',
          signBank: '',
          minPrice: '',
          maxPrice: '',
        },
        currPage: 1
      }, () => this.httpMySearchCarList())
    } else {
      this.setState({
        isOpened: false,
        currPage: 1
        //   form:e?{carModelName:'',
        // signBank:'',
        // minPrice:'',
        // maxPrice:''}:this.state.form
      }, () => this.httpMySearchCarList()
      )
    }
  }
  subStr(carModelName) {
    if (carModelName & carModelName.length > 20) {
      carModelName = carModelName.substr(0, 20) + '...'
    }
    return carModelName
  }
  clickSixModal() {
    this.setState({
      isOpened: true
    })
  }
  onCancel() {
    this.setState({
      showDialog: false,
    })
  }
  onSure() {
    this.onCancel()
    Taro.navigateTo({
      url: `/pages/myinfo/authentication`
    })
  }
  secodeClick(id) {
    Taro.navigateTo({
      url: `/pages/mortgage/applyform?editId=${id}`
    })
  }

  render() {
    const tabList = [{ title: '审核中' }, { title: '已完结' }]

    const {
      list,
      isShow,
      handle,
      scrollHeight,
      status,
      form,
      isOpened,
      signBankisOpened,
      showDialog
    } = this.state
    const { active } = this.props
    const { id } = this.$router.params
    const actionCom = [{
      text: '取消',
      style: {
        backgroundColor: '#6190E8'
      }
    },
    {
      text: '确认',
      style: {
        backgroundColor: '#FF4949'
      }
    }]
    return (
      <View className='b_index b_mortgage'>
        {!id && <View className='b_drawback__box_search flex-box' style={'position:relative'}>
          <DAtInpute onChange={this.filterSearch.bind(this)} value={form.carModelName}
            placeholder="搜索车型名称"></DAtInpute>
          <AtButton size="small" className="filter-btn at-icon at-icon-chevron-down" onClick={this.clickSixModal.bind(this)} type='secondary' >筛选</AtButton>
          <View>
            <AtActionSheet onClose={() => this.setState({ isOpened: false })} className={"at-select-one actionFilter " + (process.env.NODE_ENV === 'development' ? 'devAct' : 'proAct')} isOpened={isOpened} >
              <View className='pad'>
                <View className='at-select-one__type pad at-row'>

                  <DAtInpute className='at-col'
                    onChange={(minPrice) => this.setState({ form: { ...form, minPrice } })} value={form.minPrice}
                    placeholder="最小金额"></DAtInpute>
                  <Text className='p-pad'> - </Text>
                  <DAtInpute className='at-col'
                    onChange={(maxPrice) => this.setState({ form: { ...form, maxPrice } })}
                    value={form.maxPrice}
                    placeholder="最大金额"></DAtInpute>

                </View>
                <View className=' pad at-select-one__title_cancel' onClick={() => this.setState({ signBankisOpened: true })}>
                  <AtInput
                    editable={false}
                    name='value'
                    className='selfBank'
                    title='签件银行：'
                    border
                    type='text'
                    placeholder='请选择银行'
                    value={form.signBank}

                  ><Text className='at-icon at-icon-chevron-down' /></AtInput>
                </View>
              </View>
              <View className='at-select-one__title'>
                <View className='at-select-one__title_cancel' onClick={this.handCloseSix.bind(this, 1)} >{'重置'}</View>
                <View className='at-select-one__title_item'>{ }</View>
                <View className='at-select-one__title_submit' onClick={this.handCloseSix.bind(this)}>{'确定'}</View>
              </View>
            </AtActionSheet>
          </View>
        </View>/* <AtInput
	     				  clear
	     				  title={<View className='at-icon at-icon-search' />}
	     				  type='text'
	     				  maxLength='4'
	     				  placeholder='搜索车商名称'
	     				  value={this.state.entName}
	     				  }
	     				/>*/}

        <View className='b_index__content'>
          {list.length > 0 && <ScrollView
            scrollY
            scrollWithAnimation
            lowerThreshold='20'
            style={`height:${scrollHeight - 100}PX`}
            onScrollToLower={this.onScrollEnd}
          >
            {
              list && list.map((item, i) => {
                /*<AtSwipeAction options={actionCom}  onClick={this.onClickAction.bind(this)} >*/
                /*</AtSwipeAction>*/
                return (((id && item.entId == id) || !id) && <Dmorinfo key={i}
                  place={item.status}
                  bank={item.signBank}
                  nameList={[this.subStr(item.carModelName)]}
                  infoList={['外观颜色:', item.outColor]}
                  mormoney={item.loanPrice}
                  icon={item.icon}
                  company={item.entName}
                  clock={this.filterTime(item)}
                  item={item}
                  secodeText={item.status == 2 && '重新提交'}
                  money={item.carGuiPrice}
                  firstClick={this.onFirstClick.bind(this, item)}
                  firstText={active ? '' : '取消申请'}
                  onDetail={this.handleDetail.bind(this, item)}
                  secodeClick={this.secodeClick.bind(this, item.id)}
                ></Dmorinfo>)
              })
            }
            {
              list.length > 0 && status && <View className='b_index__more'>暂无更多</View>
            }
          </ScrollView>}
        </View>

        {
          list.length === 0 && <DItemError></DItemError>
        }

        <View>
          <DModal
            isShow={isShow}
            text={`您确认${handle}？`}
            onFirst={this.onCancelHandle.bind(this)}
            onLast={this.onDelHandle.bind(this)}
            onCancel={this.onCancelHandle.bind(this)}></DModal>
        </View>
        <AtActionSheet onClose={() => this.setState({ signBankisOpened: false })} isOpened={signBankisOpened} title='请选择银行卡所属银行'>
          {belongToBankList.map((item) => {
            return <AtActionSheetItem onClick={this.handleActionSheet.bind(this, item)} key={item}>{item}</AtActionSheetItem>
          })
          }
        </AtActionSheet>

        <View className='b_index__createform' onClick={this.onHandleForm.bind(this)}>
          <View className='b_index__createform_box'>
            <View className='b_index__createform_font'>按揭</View>
            <View className='b_index__createform_font'>申请</View>
          </View>
        </View>

        <Ddialog isShow={showDialog} content="为了您的交易安全，请进行信息认证 信息认证后可或得更多权限" btnText="信息认证" onCancel={this.onCancel.bind(this)} onSure={this.onSure.bind(this)}></Ddialog>
      </View>
    )
  }
}

DMortgageList.defaultProps = {
  className: '',
  active: 0,
}

DMortgageList.PropsType = {
  className: PropsType.oneOfType[PropsType.string, PropsType.object],
  active: PropsType.string
}
